﻿using System;
using Comdiv.QWeb.Serialization;

namespace Comdiv.QWeb.Renders {
	/// <summary>
	/// this render usefull for cached application api - wraps JS result to call of storing
	/// js object into window.qweb.embedStorage[actionname]
	/// </summary>
	public class EmbedJsonRender : IRender {
		#region IRender Members

		public void Render(QWebContext context) {
			context.ContentType = context.get("ajax", false) ? "application/json" : "text/javascript";

			context.Output.Write(
				@"
			if(!window.qweb)window.qweb={};
			if(!window.qweb.embedStorage)window.qweb.embedStorage={};
			window.qweb.embedStorage.");
			context.Output.Write(context.ActionName.Replace(".", "__"));
			context.Output.Write("=");
			if (null == context.ActionResult) context.Output.Write("null");
			else {
				new JsonSerializer().serialize("result", context.ActionResult, context.Output);
			}
			context.Output.Write(";");
		}

		public void RenderError(Exception error, QWebContext context) {
			context.Output.Write(new JsonSerializer().serialize("error", error));
		}

		public bool NeedResult {
			get { return true; }
		}

		#endregion
	}
}